import { login as loginApi, getInfo } from '@/api/user'
import { removeToken } from '@/utils/auth'
import { resetRouter } from '@/router'

const getDefaultState = () => {
  return {
    user: null
  }
}

const state = getDefaultState();

const mutations = {
  setUser(state, payload) {
    state.user = payload;
  },
  resetState(state) {
    Object.assign(state, getDefaultState());
  }
}

const actions = {
  login({ commit }, userInfo) {
    return new Promise((resolve, reject) => {
      loginApi(userInfo).then((res) => {
        var { data } = res;
        if (data) {
          commit("setUser", data);
          resolve();
        } else {
          reject(res);
        }
      }).catch((err) => {
        reject(err);
      });
    });
  },

  // get user info
  getInfo({ commit, state }) {
    return new Promise((resolve, reject) => {
      getInfo().then(response => {
        if (response.code === 401) {
          reject(res.msg);
        } else {
          commit("setUser", response.data);
          resolve();
        }
      }).catch(error => {
        reject(error);
      })
    })
  },

  logout({ commit, state }) {
    return new Promise((resolve, reject) => {
      removeToken()
      resetRouter()
      commit('resetState');
      resolve()
    }).catch(error => {
      reject(error)
    })
  },

  // remove token
  resetToken({ commit }) {
    return new Promise(resolve => {
      removeToken() // must remove  token  first
      commit('resetState');
      resolve();
    })
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}

